﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Threading;
using Eswat.Client.Wpf.ViewModels;

namespace Eswat.Client.Wpf
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		private readonly TestRunnerViewModel _viewModel;

		public MainWindow()
		{
			InitializeComponent();

			this._viewModel = new TestRunnerViewModel();

			this.DataContext = this._viewModel;
		}

		private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
		{
			if (e.Key == System.Windows.Input.Key.F5)
			{
				this._viewModel.RunTestCommand.Execute(this);
			}
		}

		private void lstTestRunners_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
		{
			var runtime = this._viewModel.SelectedTestRuntime.ToLowerInvariant();

			string sampleTestScriptPath = null;

			if (runtime == "razor") sampleTestScriptPath = "TestScriptSamples/Razor.cshtml";
			else if (runtime == "powershell") sampleTestScriptPath = "TestScriptSamples/PowerShell.ps1";
			else if (runtime == "ironpython") sampleTestScriptPath = "TestScriptSamples/IronPython.py";
			else if (runtime == "ironruby") sampleTestScriptPath = "TestScriptSamples/IronRuby.rb";

			if (sampleTestScriptPath == null) this._viewModel.TestScriptContent = string.Empty;
			else
			{
				try
				{
					var resourceStream = Application.GetResourceStream(new Uri(sampleTestScriptPath, UriKind.Relative));

					var reader = new StreamReader(resourceStream.Stream);

					this._viewModel.TestScriptContent = reader.ReadToEnd();
				}
				catch (IOException)
				{
					// resource not found
					this._viewModel.TestScriptContent = string.Empty;
				}
			}
		}
	}
}
